package com.flux

import android.app.Activity
import android.app.Application
import android.os.Bundle

import com.flux.action.SubscriptionManager
import com.flux.dispatcher.Dispatcher
import com.flux.dispatcher.RxBus
import com.flux.utils.LogUtil

/**
 * Created by marcel on 09/09/15.
 * Main class, the init method of this class must be called onCreate of the Application and must
 * be called just once. This class will automatically track the lifecycle of the application and
 * unregister all the remaining subscriptions for each activity.
 */
class RxFlux private constructor(application: Application) : Application.ActivityLifecycleCallbacks {
    /**
     * the instance of the RxBus in case you want to reused for something else
     */
    private val rxBus: RxBus = RxBus
    /**
     * the instance of the dispatcher
     */
    val dispatcher: Dispatcher = Dispatcher
    /**
     * the instance of the subscription manager in case you want to reuse for something else
     */
    val subscriptionManager: SubscriptionManager
    private var activityCounter: Int = 0

    init {
        dispatcher.init(rxBus)
        this.subscriptionManager = SubscriptionManager
        activityCounter = 0
        application.registerActivityLifecycleCallbacks(this)
    }

    override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
        activityCounter++
    }

    override fun onActivityStarted(activity: Activity) {}

    override fun onActivityResumed(activity: Activity) {}

    override fun onActivityPaused(activity: Activity) {}

    override fun onActivityStopped(activity: Activity) {}

    override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        activityCounter--
        if (activityCounter == 0) {
            RxFlux.shutdown()
        }
    }

    companion object {

        private var instance: RxFlux? = null

        fun init(application: Application): RxFlux {
            if (instance != null) throw IllegalStateException("Init was already called")
            synchronized(Dispatcher::class) {
                if (instance == null) {
                    instance = RxFlux(application)
                }
            }
            return instance!!
        }

        fun shutdown() {
            if (instance == null) return
            instance!!.subscriptionManager.clear()
        }
    }
}